const e = require('express')
const express = require('express')
const database = require('../../database')

const router = express.Router()

router.post('/register', (request, response) => {
    const info = request.body//别发多的数据来
    const checkregister = async () => {
        let invalidUsername = await new Promise(resolve => {
            database.query('select * from user where username = ?', [info.username], (error, result) => {
                if(error) {
                    response.status(417).end()//执行失败状态码417
                } else if(result.length) {
                    resolve(true)
                } else {
                    resolve(false)
                }
            })
        })
        let invalidNickname = await new Promise(resolve => {
            database.query('select * from user where nickname = ?', [info.nickname], (error, result) => {
                if(error) {
                    response.status(417).end()
                } else if(result.length) {
                    resolve(true)
                } else {
                    resolve(false)
                }
            })
        })
        if(invalidUsername || invalidNickname) {
            response.send({
                allowed: false,
                invalidUsername,
                invalidNickname
            })
        } else {
            const sql = 'insert into user values(?, ?, ?, ?)'
            database.query(sql, [info.username, info.password, info.nickname, 'user'], (error, result) => {
                if(error || result.affectedRows != 1) {
                    response.status(417).end()
                } else {
                    response.send({
                        allowed: true,
                        invalidUsername,
                        invalidNickname
                    })
                }
            })
        }
    }
    checkregister()
})

module.exports = router